#!/bin/bash

# 根据传入参数设置 appENV
if [[ $1 == "pro" ]]; then
    appENV="pro"
else
    appENV="dev"
fi


# flutter clean 再删除 build文件 再 flutter pub get 一遍 这样确保没有问题
flutter clean
rm -r build
flutter pub get

# 读取 version 字段，去掉空格
version=$(grep '^version:' pubspec.yaml | awk -F': ' '{print $2}' | tr -d '[:space:]')

# 检查 version 是否非空
if [[ -z "$version" ]]; then
    echo "Error: Version not found in YAML file!"
    exit 1
fi

# 正则匹配 version 格式（1.0.0+xxx）
if [[ "$version" =~ ^([0-9]+\.[0-9]+\.[0-9]+)\+([0-9]+)$ ]]; then
    base_version="${BASH_REMATCH[1]}"
    build_number=$(( ${BASH_REMATCH[2]} + 1000 ))

    echo "Version: $base_version"
    echo "Build Number: $build_number"
else
    echo "Error: Version format is incorrect! Found: $version"
    exit 1
fi

current_time=$(date +"%Y%m%d")

# 获取传入的参数，默认为 1
param=${2:-1}

# 判断参数值
case $param in
    1)
       # 打包含 arm64-v8a 和 armeabi-v7a 架构的混合包
       flutter build apk --tree-shake-icons  --dart-define=APP_ENV=$1
       appRelease="app-release"
        ;;
    32)
        # 只打 armeabi-v7a 架构的包
        flutter build apk --target-platform android-arm --split-per-abi --tree-shake-icons  --dart-define=APP_ENV=$1
        appRelease="app-armeabi-v7a-release"
        ;;
    *)
        # 只打 arm64-v8a 架构的包
        flutter build apk --target-platform android-arm64 --split-per-abi --tree-shake-icons  --dart-define=APP_ENV=$1
        appRelease="app-arm64-v8a-release"
        ;;
esac

echo "参数=$appRelease"

cd ./build/app/outputs/flutter-apk

cp ${appRelease}.apk app${appENV}_${current_time}_V${base_version}+${build_number}.apk

mv app${appENV}_${current_time}_V${base_version}+${build_number}.apk ../../../../
cd ../../../../
